package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.CluePoolDO;
import com.qk.domain.user.UserDO;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;

import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import com.qk.vo.cluetrackrecord.ClueTrackRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * &#064;author：zzq
 * &#064;createTime：2025/10/13 16:55
 * &#064;description： 线索管理业务层实现类
 */
@Service
@Slf4j
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    @Transactional
    public void toFalseClue(Integer id, MarkFalseClueDto dto) {
        //根据id查找线索
        Clue clue = this.getById(id);
        //更新clue状态为4伪线索
        clue.setStatus(ClueStatusConstants.FAKE_CLUE);
        //更新clue
        this.updateById(clue);
        //添加线索跟进记录
        ClueTrackRecord clueTrackRecord = ClueTrackRecord.builder()
                .clueId(null)
                .clueId(clue.getId())
                .userId(clue.getUserId())
                .subject(clue.getSubject())
                .level(clue.getLevel())
                .record(dto.getRemark())
                .nextTime(clue.getNextTime())
                .type(ClueTrackRecordType.FAKE)
                .falseReason(dto.getReason())
                .createTime(LocalDateTime.now())
                .build();
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Transactional
    @Override
    public void toBusiness(Integer id) {
        //1.根据id查询线索信息
        Clue clue = this.baseMapper.selectById(id);
        //2.更新线索状态为商机
        //2.1更新线索状态
        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);
        //2.2更新时间
        clue.setUpdateTime(LocalDateTime.now());
        //2.3更新到clue表
        this.baseMapper.updateById(clue);
        //3.将线索信息组装成商机,添加到商机表
        //3.1拷贝数据
        Business business = BeanUtil.copyProperties(clue, Business.class);
        //3.2处理拷贝后的数据
        //①商机id设为null
        business.setId(null);
        //②设置商机创建和修改时间
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        //③重置下次跟进时间
        business.setNextTime(null);
        //④重置商机专员id
        business.setUserId(null);
        //⑤设置商机状态
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        //⑥设计商机从属的线索id
        business.setClueId(id);
        //3.3添加到商机表
        this.businessMapper.insert(business);
    }

    @Transactional//事务 确保数据一致性
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        //1.获取信息基本信息更新线索表
        //1.1将dto转成实体类
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        //1.2补全更新时间
        clue.setUpdateTime(LocalDateTime.now());
        //1.3处理状态 第一次被跟进状态2待跟进改为状态3跟进中
        if (dto.getStatus() == ClueStatusConstants.WAIT_FOLLOW_UP) {
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        //1.4更新到clue表
        this.baseMapper.updateById(clue);
        //2.获取跟进记录信息 插入线索记录表哦clue_track_record表
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        //2.1补全创建时间
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        //2.2将id设为null
        clueTrackRecord.setId(null);
        //2.3设置线索id
        clueTrackRecord.setClueId(clue.getId());
        //2.4设置线索跟进记录类型默认正常跟进
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        //2.5插入到clue_track_record表
        clueTrackRecordMapper.insert(clueTrackRecord);

    }


    @Override
    public ClueVO getClueInfoById(Integer id) {
        //1.根据id查询线索表获取基础线索信息
        Clue clue = this.baseMapper.selectById(id);
        //2.根据用户id获取用户姓名
        UserDO user = userMapper.get(clue.getUserId());
        String username;
        if (ObjectUtil.isEmpty(user)) {
            username = null;
        } else {
            username = user.getName();
        }
        //3.根据线索id查询线索跟进记录表获取跟进记录信息
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id));
        //4.组装数据
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueTrackRecordVO.class);
            vo.setAssignName(username);
            return vo;
        }).toList();
        //设置跟进记录
        clueVO.setTrackRecords(list);
        return clueVO;
    }

    @Override
    public void addClue(ClueDTO dto) {
        //参数校验
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //将dto转成实体类
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        //数据补全
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        //保存数据到clue表
        this.baseMapper.insert(clue);
    }

    @Override
    public PageResult<ClueDO> clueList(ClueListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<ClueDO> page = (Page<ClueDO>) this.baseMapper.selectByPage(dto);
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public PageResult<CluePoolDO> cluePoolList(CluePoolListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<CluePoolDO> page = (Page<CluePoolDO>) this.baseMapper.selectPoolByPage(dto);
        return PageResult.<CluePoolDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}
